package com.zjs.redis.redisson;

import com.util.result.Message;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Redisson操作Redis实现分布式锁
 */
@Service
@Slf4j
public class RedissonServiceImpl {

    @Resource
    private RedissonClient redissonClient;

    public Message redissonRock() {
        int random = (int)(1+Math.random()*(10000-1+1));
//        RLock rLock = redissonClient.getLock("redisson:" + System.currentTimeMillis() + random);
        RLock rLock = redissonClient.getLock("redisson:lock");
        boolean result = false;
        try {
//            log.info("线程{}开始获取锁时间：{}", Thread.currentThread().getName(), new Date());
            result = rLock.tryLock(0, TimeUnit.SECONDS);
//            log.info("线程{}锁结果返回时间：{}", Thread.currentThread().getName(), new Date());
//            log.info("获得锁的结果：{}", result);
            if (result) {
                log.info("获得锁");
                Thread.sleep(100 * 1000);
                log.info("业务执行完成");
            }
//            else {
//                log.info("获取锁失败");
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (result) {
                rLock.unlock();
            }
        }
        return Message.success("获得锁的结果:" + result);
    }
}
